package com.example.mall.common.utils;

import com.example.mall.common.core.exception.ServerException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Jackson序列化和反序列化-增强工具类
 *  - 序列化 Object -> Json
 *  - 序列化 Map -> Json
 *  - 序列化 List -> Json
 *
 */
@Component
public class GeneriAndJson {
    private static ObjectMapper mapper;

    @Autowired
    public void setMapper(ObjectMapper mapper) {
        GeneriAndJson.mapper = mapper;
    }

    /**
     * object -> json
     * @param o
     * @param <T>
     * @return
     */
    public static <T> String objectToJson(T o) {
        try {
            return GeneriAndJson.mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new ServerException(9999);
        }
    }

    /**
     * json -> object, 兼容 list
     * @param s
     * @param tr
     * @param <T>
     * @return
     */
    public static <T> T jsonToObject(String s, TypeReference<T> tr) {
        if (s == null)
            return null;
        try {
            T o = GeneriAndJson.mapper.readValue(s, tr);
            return o;
        } catch (JsonProcessingException e) {
            throw new ServerException(9999);
        }
    }
}
